import requests
import os,time
from bs4 import BeautifulSoup
from Levenshtein import distance
import shutil
import configparser

"Config Area"
conf = configparser.ConfigParser()
conf.read(r".\\config.ini", encoding="utf-8")
INI_method = r"http://"
INI_server = r"10.60.1.250"
INI_cookie = str(conf.get("BNDSOJ","cookie"))
INI_local = r".\\download\\"
INI_homeworkid = int(conf.get("BNDSOJ","homeworkid"))
INI_homeworklst = int(conf.get("BNDSOJ","homeworklst"))
INI_ext = r".code"
INI_warnning = int(conf.get("BNDSOJ","warnning"))
"Config Area"

server = INI_method + INI_server
headers = {
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Accept-Encoding" : "gzip, deflate",
"Accept-Language" : "zh-CN,zh;q=0.9",
"Cache-Control" : "max-age=0",
"Connection" : "keep-alive",
"Cookie" : INI_cookie,
"Host" : INI_server,
"Upgrade-Insecure-Requests" : "1",
"User-Agent" : "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36",
}

def getfinishresult(id,row):
	result = []
	html = requests.get(server+"/homework/manage/result?id="+str(id),headers=headers)
	html.encoding = "utf-8"
	soup = BeautifulSoup(html.text,'html.parser')
	table = soup.find("table").find("tbody")
	for user in table.find_all("tr"):
		try:
			username = user.find("span",class_="uoj-username").text
			all_td = user.find_all("td")
			submit = all_td[row].find("a")
			if submit is not None and submit.string != "0":
				score = submit.string
				code = server+submit.get("href")
				result.append([username,score,code])
		except:
			print("ERROR")
	return result

def downloadcode(userlist):
	for user in userlist:
		try:
			print("DOWNLOADING",user[0])
			html = requests.get(user[2],headers=headers)
			html.encoding = "utf-8"
			soup = BeautifulSoup(html.text,'html.parser')
			code = soup.find("code")
			if code is not None:
				with open(INI_local+user[0]+INI_ext,"w",encoding="utf-8") as file:
					file.write(code.string.replace("\r",""))
			else:
				with open(INI_local+user[0]+INI_ext,"w",encoding="utf-8") as file:
					file.write("empty")
		except:
			print("ERROR")

def comparecode(user1,user2):
	code1 = open(INI_local+user1+INI_ext,"r").read()
	code2 = open(INI_local+user2+INI_ext,"r").read()
	if distance(code1,code2) <= int(INI_warnning):
		return True
	return False

if __name__ == "__main__":
	shutil.rmtree(INI_local)
	os.makedirs(INI_local)
	print("GETTING HOMEWORK LIST...")
	userlist = getfinishresult(INI_homeworkid,INI_homeworklst)
	print("DOWNLOADING USER CODE...")
	downloadcode(userlist)
	print("START COMPARING USER CODE...")
	for user1 in range(0,len(userlist)):
		for user2 in range(user1+1,len(userlist)):
			if comparecode(userlist[user1][0],userlist[user2][0]):
				print("SIMILAR :",userlist[user1][0]," ",userlist[user2][0])
	print("COMPARE FINISHED!")